package com.xzp.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzp.yygh.common.exception.YyghException;
import com.xzp.yygh.common.helper.JwtHelper;
import com.xzp.yygh.common.result.Result;
import com.xzp.yygh.common.result.ResultCodeEnum;
import com.xzp.yygh.model.user.UserInfo;
import com.xzp.yygh.user.service.UserInfoService;
import com.xzp.yygh.user.utils.ConstantPropertiesUtil;
import com.xzp.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(HttpSession session){
        HashMap<String, String> map = new HashMap<>();
        try {
            String appid = ConstantPropertiesUtil.WX_OPEN_APP_ID;
            String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
            String scope = "snsapi_login";
//            String response_type = ConstantPropertiesUtil.WX_OPEN_APP_SECRET;
            map.put("appid", appid);
            map.put("redirectUri", redirectUri);
            map.put("scope", scope);
            map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
//            map.put("response_type", response_type);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Result.ok(map);
    }

    /**
     * 微信登录回调
     *
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("callback")
    public String callback(String code, String state) {
        //获取授权临时票据
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);

        // 参数不能为空
        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {
//            log.error("非法回调请求");
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");



        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            // HttpClient访问accessTokenUrl， 获得access_token
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        System.out.println("使用code换取的access_token结果 = " + result);
        // 拼接地址 获取userInfoUrl
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");

        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
        String resultUserInfo = null;
        try {
            resultUserInfo = HttpClientUtils.get(userInfoUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
        System.out.println("使用access_token获取用户信息的结果 = " + resultUserInfo);
        // 现将string转为json
        jsonObject = JSONObject.parseObject(resultUserInfo);
        String nickname = jsonObject.getString("nickname");
        String headimgurl = jsonObject.getString("headimgurl");
        // 根据openid查询数据库
        UserInfo userInfo = userInfoService.selectUserInfoByOpenId(openid);
        // 有openid和phone
//        if(userInfo!=null && !StringUtils.isEmpty(userInfo.getPhone())) {
//            // jwt生成token
//            token = JwtHelper.createToken(userInfo.getId(), name);
//        }
        if(userInfo==null){
            // 第一次微信登录，将数据加入数据库
            userInfo = new UserInfo();
            userInfo.setStatus(1);
            userInfo.setOpenid(openid);
            userInfo.setNickName(nickname);
            userInfoService.save(userInfo);
        }
        // 获取name
        String name = "";
        name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = nickname;
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        if(!StringUtils.isEmpty(userInfo.getPhone())){
            openid = "";
        }
        // jwt生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        System.out.println(token);
        System.out.println(openid);
        System.out.println(name);

        return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+ token +"&openid="+ openid+"&name="+URLEncoder.encode(name);


    }
}
